package com.gs.SynAntiWandering.util;

import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.LocaleList;
import android.util.DisplayMetrics;

import com.gs.SynAntiWandering.R;
import com.gs.SynAntiWandering.constant.AllConstants;

import java.util.Locale;

public class LanguageUtils {
    private static volatile LanguageUtils instance;

    private LanguageUtils() {
    }

    public static LanguageUtils getInstance() {
        if (null == instance) {
            synchronized (LanguageUtils.class) {
                if (instance == null) {
                    instance = new LanguageUtils();
                }
            }
        }
        return instance;
    }

    public Context change(Locale locale) {
        Context context = AppUtil.getInstance().getContext();
        Resources resources = context.getApplicationContext().getResources();
        Configuration config = resources.getConfiguration();
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
            config.setLocale(locale);
        } else {
            config.locale = locale;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            config.setLocales(new LocaleList(locale));
            context = context.createConfigurationContext(config);
        } else {
            DisplayMetrics dm = resources.getDisplayMetrics();
            resources.updateConfiguration(config, dm);
        }
        AppUtil.getInstance().initContext(context);
        return context;
    }

    public Locale getCurLocale() {
        return getLanguageInt() == 2 ? Locale.ENGLISH : Locale.TAIWAN;
    }

    public int getStrLanguage() {
        return getLanguageInt() == 2 ? R.string.english : R.string.chinese;
    }

    public String getLanguage() {
        return getLanguageInt() == 2 ? "en-US,en" : "zh-TW,zh";
    }

    public int getLanguageInt() {
        return SPUtil.getInstance().getInt(AllConstants.LANGUAGE, 1);
    }


    /**
     * 切换语言时，要重新初始化其他进程的Resources的语言
     */
    public void initResources(Context context) {
        Resources res = context.getResources();
        Configuration configuration = res.getConfiguration();
        Locale locale = getCurLocale();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLocale(locale);
        } else {
            configuration.locale = locale;
        }
        // updateConfiguration
        DisplayMetrics dm = res.getDisplayMetrics();
        res.updateConfiguration(configuration, dm);
    }
}
